from mcp.server.fastmcp import FastMCP
import threading
import anyio

from invoice.models import *
#声明MCP服务实例
mcp =  FastMCP("mcp-invoice-server",host="0.0.0.0",port=5000)

@mcp.tool()
def saveInvoices(invoices:list):
    """
     保存发票信息（可以是单条或多条）
    :param invoices 列表类型-发票列表
    :return 类型类型：是否成功
    """
    print("调用了发票保存MCP tool方法{saveInvoice}:",invoices)
    #把参数写入到文件
    with open("invoice.log", "w",encoding="utf-8") as f:
        f.write(invoices.__str__())
    # invoice_json_str是一个数组json字符串
    # invoice_list = json.loads(list_json_str)
    for invoice in invoices:
        #调用发票模型及存储数据
        # result = createInvoice(invoice)
        createInvoice(invoice)
    return "成功保存发票"


def start_mcp_background():
    """在新线程中启动 MCP 服务"""

    def run_mcp():
        # 确保新线程有自己的 Django 上下文
        import django
        django.setup()

        print("========== 在后台线程启动 MCP 服务 =================")
        try:
            # 直接使用 anyio 运行异步方法
            anyio.run(mcp.run_sse_async)
        except Exception as e:
            print(f"MCP 服务启动失败: {e}")

    # 创建并启动守护线程
    thread = threading.Thread(target=run_mcp, daemon=True)
    thread.start()
    print("MCP 服务已在后台线程启动")


# 在 Django 启动时调用此函数
if __name__ == "__main__":
    start_mcp_background()
# if __name__ == "__main__":
#     mcp.run(transport="sse")
